package com.mianyang.zhangsan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mianyang.zhangsan.common.util.CacheHelper;
import com.mianyang.zhangsan.common.util.CommonUtils;
import com.mianyang.zhangsan.common.util.StringUtils;
import com.mianyang.zhangsan.exception.SecServiceException;
import com.mianyang.zhangsan.model.dto.SecBankChart;
import com.mianyang.zhangsan.model.dto.SecProblemAnswerDto;
import com.mianyang.zhangsan.model.entity.SecAnswer;
import com.mianyang.zhangsan.model.entity.SecBank;
import com.mianyang.zhangsan.model.entity.SecPaperBank;
import com.mianyang.zhangsan.model.entity.SecPaperBankGroup;
import com.mianyang.zhangsan.model.entity.SecProblem;
import com.mianyang.zhangsan.model.entity.SecProblemGroup;
import com.mianyang.zhangsan.model.entity.SecStaticData;
import com.mianyang.zhangsan.service.SecAnswerService;
import com.mianyang.zhangsan.service.SecBankService;
import com.mianyang.zhangsan.mapper.SecBankMapper;
import com.mianyang.zhangsan.service.SecPaperBankService;
import com.mianyang.zhangsan.service.SecProblemService;
import com.mianyang.zhangsan.service.SecStaticDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author jiangjr
*/
@Service
public class SecBankServiceImpl extends ServiceImpl<SecBankMapper, SecBank>
    implements SecBankService{
    @Autowired
    private SecStaticDataService staticDataService;
    @Autowired
    private SecPaperBankService paperBankService;
    @Autowired
    private SecProblemService problemService;
    @Autowired
    private SecAnswerService answerService;

    @Override
    public Page<SecBank> selectBankByPage(SecBank bank, Integer current, Integer pageSize) {
        QueryWrapper<SecBank> wrapper = new QueryWrapper<>();
        if (bank.getBankType() != null) {
            wrapper.eq("bank_type", bank.getBankType());
        }
        if (StringUtils.isNotEmpty(bank.getBankName())) {
            wrapper.like("bank_name", bank.getBankName());
        }
        return page(new Page<>(current, pageSize), wrapper);
    }

    @Override
    public List<SecBankChart> analysis() {
        // 查询所有的题库
        List<SecBank> banks = list();
        List<SecBankChart> charts = new ArrayList<>();
        List<String> coordinate = new ArrayList<>();
        List<SecStaticData> bankTypes = staticDataService.getCache("BANK_TYPE", "");
        if (CommonUtils.isNotEmpty(bankTypes) && CommonUtils.isNotEmpty(banks)) {
            SecBankChart chart = new SecBankChart();
            String[] typeArray = bankTypes.stream().sorted((o1, o2) -> o1.getSortId() - o2.getSortId())
                    .map(SecStaticData::getCodeName).toArray(String[]::new);
            coordinate = banks.stream().map(bank -> typeArray[bank.getBankType()]).collect(Collectors.toList());
            chart.setContainer("chart");
            chart.setCoordinate(coordinate);
            // 查询题库关联的试卷数量
            List<SecPaperBankGroup> paperBanks = paperBankService.selectDataGroupBy("bank_id");
            List<SecProblemGroup> problems = problemService.selectDataGroupBy("bank_id");
            List<Integer> papers = new ArrayList<>();
            List<Integer> problemList = new ArrayList<>();
            banks.forEach(bank -> {
                paperBanks.stream()
                        .filter(item -> item.getBankId().equals(bank.getBankId()))
                        .findFirst().ifPresent(item -> papers.add(item.getCount()));
                problems.stream()
                        .filter(item -> item.getBankId().equals(bank.getBankId()))
                        .findFirst().ifPresent(item -> problemList.add(item.getCount()));
            });
            chart.setPapers(papers);
            chart.setProblems(problemList);
            charts.add(chart);
        }
        //
        return charts;
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void saveProblemAndAnswer(SecProblemAnswerDto problemInfo) {
        // 保存问题信息
        SecProblem problem = problemInfo.getProblem();
        Long problemId = problem.getProblemId();
        if (problemId != null) {
            throw new SecServiceException("新增操作不能带有 主键编号");
        }
        problemService.save(problem);
        problemId = problem.getProblemId();
        // 题库数量 +1
        SecBank bank = getById(problem.getBankId());
        Integer problems = bank.getBankProblems();
        bank.setBankProblems(problems + 1);
        updateById(bank);
        List<SecAnswer> answers = problemInfo.getAnswers();
        // 保存答案
        Long answerId = answerService.updateAndGetRightId(answers, problemId);
        // 更新问题正确答案编号
        problem.setProblemRight(answerId);
        problemService.updateById(problem);
    }
}




